package entity;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

public class ShoppingCart {
    HashMap<String, GoodsItem> hashMap = new HashMap<>();

    public void update(GoodsItem goodsItem) {
        String cId = goodsItem.getCommodity().getcId();
        if (hashMap.containsKey(cId)) {
            GoodsItem now = hashMap.get(cId);
            now.setQuality(goodsItem.getQuality());
        } else {
            hashMap.put(cId, goodsItem);
        }
    }

    public void remove(String cId) {
        if (hashMap.containsKey(cId)) {
            hashMap.remove(cId);
        }
    }

    //返回购物车中的集合
    public Collection<GoodsItem> getMap() {
        return hashMap.values();
    }

    public double getTotal() {
        double amount = 0.0;
        for (Iterator<GoodsItem> i = getMap().iterator(); i.hasNext(); ) {
            GoodsItem next = i.next();
            Commodity commodity = next.getCommodity();
            amount += next.getQuality() * commodity.getcPrice();
        }
        long val = Math.round(amount * 100);
        return val / 100.0;
    }

    public void clear() {
        hashMap.clear();
    }
}
